/*
 * @Author: kuangw
 * @Date: 2020-11-23 09:34:56
 * @LastEditTime: 2020-11-23 11:47:14
 * @LastEditors: Please set LastEditors
 * @Description: 这个文件封装nodejs与文件相关操作
 * @FilePath: \nodeJs\base-fs.js
 */

const fs = require('fs')

// ^ 定义新函数 writeFs

const writeFs = (path, content, { encoding, flag } = { encoding: "utf-8", flag: 'a' }) => new Promise((resovle, reject) => {
  fs.writeFile(path, content, { encoding, flag }, (err, data) => {
    if (err) return reject(err);
    resovle(data);
  })
})

// ^ 创建一个文件写入流

const createFWS = (path) => new Promise((reslove, reject) => {
  return  fs.createWriteStream(path)
})


// ^ 将&#x格式的字符转换为汉字
const parseUncode = (uncode) => {
  return unescape(uncode.replace(/&#x/g, '%u').replace(/;/g, ''))
}

// ^ 创建文件夹
const mkdir = (path) => new Promise((reslove, reject) => {

  fs.mkdir(path, { recursive: true }, (err) => {
    if (err) {
      console.log(err);
      return reject(err)
    }
    reslove()
  })
})


// ^ 删除空格等特殊符号的函数
const parseStr = (str) => {
  let reg1 = /[\/\|\\\>\<\?]/igs
  str = str.replace(reg1, '')

  // str=
  let reg = /\s+/igs
  return str.replace(reg, '-')

}



module.exports = {
  writeFs,
  parseUncode,
  mkdir,
  parseStr,
  createFWS
};
